package com.quxian.chambercommerce.util;


import javax.crypto.Cipher;
import javax.crypto.SecretKey;

/**
 * 使用3DES加密与解密,可对byte[],String类型进行加密与解密 密文可使用String,byte[]存储.
 *
 * @author York
 */
public class ThreeDES {

//	private String algorithm = "DES";
	
	// 需要注意，这个密钥不能随意更改，已被第三方系统使用
	private static final String ALGORITHM = "DES";
	// SHA-1
//	private static final String SHA1 = "SHA-1";

	// 密钥 des
	private static final String KEY = "6b65795f31322140";				// 默认密钥
   
	
	public ThreeDES(){

    }
    
	/**
	 * 将16进制字符串转换为字节
	 * 
	 * @param sBytes
	 * @return
	 */
	private static byte[] hex2byte(String sBytes) {

		byte[] bytes = new byte[sBytes.length() / 2];

		for (int i = 0; i < bytes.length; i++) {
			bytes[i] = (byte) Integer.parseInt(sBytes.substring(2 * i,
					2 * i + 2), 16);
		}

		return bytes;
	}
    
	/**
	 * 将字节转换为16进制字符
	 * 
	 * @param bytes
	 * @return
	 */
	private static String byte2hex(byte[] bytes) {

		StringBuffer sBytes = new StringBuffer();
		String stmp = "";

		for (int n = 0; n < bytes.length; n++) {
			stmp = (Integer.toHexString(bytes[n] & 0XFF));

			if (stmp.length() == 1) {
				sBytes.append("0");
				sBytes.append(stmp);
			} else {
				sBytes.append(stmp);
			}

			if (n < bytes.length - 1) {
				sBytes.append("");
			}
		}

		return sBytes.toString();
	}
	
    /**
     * 加密String明文输入,String密文输出
     *
     * @param strMing String明文
     * @return String密文
     */
    public static String getEncString(String plainText) {    	
    	plainText = changeToUnicode(plainText);
    	try{
		    	byte[] cryptograph = plainText.getBytes();
		
				byte[] key = hex2byte(KEY);
				SecretKey deskey = new javax.crypto.spec.SecretKeySpec(key, ALGORITHM);
		
				Cipher cipher;
				cipher = Cipher.getInstance(ALGORITHM);
				cipher.init(Cipher.ENCRYPT_MODE, deskey);
				cryptograph = cipher.doFinal(plainText.getBytes());
	
			return byte2hex(cryptograph);
    	}catch (Exception e) {
			// TODO: handle exception
    		e.printStackTrace();
    		return null;
		}
    }
    /**
     * 解密 以String密文输入,String明文输出
     *
     * @param strMi String密文
     * @return String明文
     * @throws Exception 
     */
    public static String getDesString(String strMi) {
    	try{
    		if(strMi == null || "".equals(strMi)){
    			return "";
    		}
	    	byte[] plainText = strMi.getBytes();
	
			byte[] key = hex2byte(KEY);
			SecretKey deskey = new javax.crypto.spec.SecretKeySpec(key, ALGORITHM);
	
			Cipher cipher;
			cipher = Cipher.getInstance(ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, deskey);
			plainText = cipher.doFinal(hex2byte(strMi));
			
			return changeToword(new String(plainText));
    	}catch (NumberFormatException e) {
		}catch (Exception e) {
		}
		return "";
    } 
    
    
    /**
     * 字符串转成unicode
     * @param str
     * @return
     */
    public static String changeToUnicode(String str){
   		  StringBuffer strBuff = new StringBuffer();
   		  for(int i=0;i<str.length();i++){
   			  String temp = Integer.toHexString(str.charAt(i));
   			  if(temp.length()!=4){
   				  temp = "00"+temp;
   			  }
   			  if(temp.equals("00d")){
   				  temp = "0"+temp;
   			  }
   			  if(temp.equals("00a")){
   				  temp = "0"+temp;
   			  }
   			  strBuff.append(temp.substring(0, temp.length()-2));
   			  strBuff.append(temp.substring(temp.length()-2, temp.length()));
   		  }
   			  String returnData = strBuff.toString();
   			  return returnData;
   			  
   		  }

   /**
    * unicode转成字符串
    * @param str
    * @return
    */
   public static String changeToword(String str){
   		String retData = null;
   		String tempStr = new String(str);
   		String[] chStr = new String[str.length()/4];
   		for(int i=0;i<str.length();i++){
   			if(i%4==3){
   				chStr[i/4] = new String(tempStr.substring(0, 4));
   				tempStr = tempStr.substring(4, tempStr.length());
   				
   			}
   		}
   		char[] retChar = new char[chStr.length];
   		for(int i=0;i<chStr.length;i++){
   			retChar[i] = (char)Integer.parseInt(chStr[i], 16);
   		}
   		retData = String.valueOf(retChar,0,retChar.length);
   		return retData;
   	}
    

    public static void main(String[] args) throws Exception {
    	String s = ThreeDES.getEncString("{'serviceId':'2010051702','params':{'APID':'应用工厂提供','Key':'应用工厂提供','Num':'13301163987'}}");
    	System.out.println(s);
    	String d = "f44741909116cd5caec21303daf79f053db3d60d1d751fef40645385647c4cdd9030f2505c806352811a010933826c7d5c3787dd225fe608d225fc1526ef09b8";
    	System.out.println(ThreeDES.getDesString(d) );
    	
    	
    }
    
}




